import { Router, Request, Response } from 'express';
import { RolesModel } from '../models/roles.model';

const router = Router();

// 获取所有角色
router.get('/', async (req: Request, res: Response) => {
  try {
    const roles = await RolesModel.findAll();
    res.json({code: 1, message: '获取成功', data: roles});
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({code: 0, message});
  }
});

// 创建角色
router.post('/', async (req: Request, res: Response) => {
  try {
    const id = await RolesModel.create(req.body);
    res.json({code: 1, message: '创建成功', data: {id}});
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({code: 0, message});
  }
});

// 为用户分配角色
router.post('/assign', async (req: Request, res: Response) => {
  try {
    const { userId, roleId } = req.body;
    const success = await RolesModel.assignRole(userId, roleId);
    if (success) {
      res.json({code: 1, message: '分配成功'});
    } else {
      res.status(400).json({code: 0, message: '分配失败'});
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({code: 0, message});
  }
});

export default router;
